﻿using System;
using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using System.Collections.Generic;
using UnityEditor;
#endif

namespace Yoozoo.Gameplay.City
{
    [ExecuteAlways]
    public class CityIndustryContainer : MonoBehaviour
    {
        [Header("对应配表里的产业建造位置ID")]
        public int industryId;

#if UNITY_EDITOR
        
        private List<MeshRenderer> _meshRenderers;
        
        void Update()
        {
            PreviewDraw();
        }
        
        private void PreviewDraw()
        {
            if (CityIndustryEditorConfig.Instance && 
                CityIndustryEditorConfig.Instance.preview)
            {
                if (CityIndustryEditorConfig.Instance.material == null)
                {
                    return;
                }
                
                if (_meshRenderers == null || _meshRenderers.Count == 0)
                {
                    _meshRenderers = new List<MeshRenderer>();
                     List<MeshRenderer> meshRenderers = transform.GetComponentsInChildren<MeshRenderer>().ToList();

                     foreach (var meshRenderer in meshRenderers)
                     {
                         var iObj = GameObject.Instantiate(meshRenderer.gameObject, CityIndustryEditorConfig.Instance.PreviewRoot);
                         iObj.transform.position = meshRenderer.gameObject.transform.position;
                         iObj.transform.rotation = meshRenderer.gameObject.transform.rotation;
                         var lossyScale = transform.lossyScale;
                         var scale = meshRenderer.gameObject.transform.lossyScale;
                         iObj.transform.localScale = new Vector3(
                             scale.x /lossyScale.x,
                             scale.y /lossyScale.y,
                             scale.z /lossyScale.z)*1.02f ;
                         MeshRenderer mr = iObj.GetComponent<MeshRenderer>();
                         mr.materials = Array.Empty<Material>();
                         mr.material = CityIndustryEditorConfig.Instance.material;
                         _meshRenderers.Add(mr);
                     }
                }
                
            }
            else
            {
                if (_meshRenderers!=null)
                {
                    foreach (var meshRenderer in _meshRenderers)
                    {
                        GameObject.DestroyImmediate(meshRenderer.gameObject);
                    }
                    _meshRenderers = null;
                }

            }
        }


        private void OnValidate()
        {
            transform.name = "Industry_" + industryId.ToString();
        }
#endif
    }
}